<template>
  <div class="flex flex-col h-screen" :class="isDarkMode ? 'bg-gray-900 text-gray-200' : 'bg-gray-50'">
    <!-- 顶部导航栏 -->
    <div class="py-3 px-4 flex items-center justify-between shadow-sm transition-all duration-500 ease-spring" :class="isDarkMode ? 'bg-gray-800' : 'bg-white'">
      <button 
        @click="toggleSidebar" 
        class="p-1.5 rounded-md transition-all duration-500 transform hover:scale-110 active:scale-95 btn-bounce"
        :class="isDarkMode ? 'hover:bg-gray-700' : 'hover:bg-gray-100'"
      >
        <font-awesome-icon icon="bars" class="transform transition-transform duration-500 ease-spring" :class="sidebarOpen ? 'rotate-90' : ''" />
      </button>
      <div class="flex items-center space-x-3">
        <button 
          @click="toggleDarkMode" 
          class="p-1.5 rounded-md transition-all duration-500 transform hover:scale-110 active:scale-95 overflow-hidden theme-switch"
          :class="isDarkMode ? 'hover:bg-gray-700' : 'hover:bg-gray-100'"
        >
          <div class="relative w-5 h-5 theme-switch-inner">
            <font-awesome-icon 
              :icon="['fas', 'sun']" 
              class="absolute inset-0 transition-all duration-500 transform"
              :class="isDarkMode ? 'opacity-100 rotate-0 scale-100' : 'opacity-0 rotate-90 scale-50'" 
            />
            <font-awesome-icon 
              :icon="['fas', 'moon']" 
              class="absolute inset-0 transition-all duration-500 transform"
              :class="isDarkMode ? 'opacity-0 -rotate-90 scale-50' : 'opacity-100 rotate-0 scale-100'" 
            />
          </div>
        </button>
        <UserMenu :isDarkMode="isDarkMode" />
      </div>
    </div>

    <!-- 侧边菜单 -->
    <div 
      v-if="sidebarOpen" 
      class="fixed inset-0 z-40 flex"
    >
      <div 
        class="fixed inset-0 bg-gray-900 transition-opacity duration-500 ease-spring" 
        :class="sidebarOpen ? 'bg-opacity-60' : 'bg-opacity-0 pointer-events-none'" 
        @click="toggleSidebar"
      ></div>
      <div 
        class="relative flex-1 flex flex-col max-w-xs w-full transform transition-all duration-700 ease-spring sidebar-enter overflow-hidden"
        :class="[
          sidebarOpen ? 'translate-x-0' : '-translate-x-full'
        ]"
      >
        <!-- 侧边栏背景效果 -->
        <div class="absolute inset-0 z-0 opacity-90 transition-all duration-500" 
             :class="isDarkMode ? 'bg-gray-900' : 'bg-gray-50'"></div>
        
        <!-- 背景装饰元素 -->
        <div class="absolute -top-20 -right-20 w-64 h-64 rounded-full bg-[#8153ff]/20 blur-3xl z-0"></div>
        <div class="absolute -bottom-10 -left-10 w-48 h-48 rounded-full bg-[#93dc24]/20 blur-3xl z-0"></div>
        <div class="absolute top-1/3 -right-10 w-40 h-40 rounded-full bg-[#8153ff]/10 blur-2xl z-0 animate-pulse-slow"></div>
        
        <!-- 侧边栏内容 -->
        <div class="flex-1 h-0 pt-6 pb-4 overflow-y-auto scrollbar-thin z-10 relative">
          <div class="flex items-center justify-between px-5 mb-6">
            <h1 class="text-lg font-bold bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent animate-gradient-x drop-shadow-sm">别学了哥</h1>
            <button 
              @click="toggleSidebar" 
              class="p-2 rounded-full transition-all duration-500 transform hover:scale-110 active:scale-95 hover:rotate-90 bg-gradient-to-r hover:from-[#8153ff]/20 hover:to-[#93dc24]/20 text-[#8153ff]"
            >
              <font-awesome-icon icon="times" class="transform transition-transform duration-500" />
            </button>
          </div>
          
          <!-- 主内容导航 -->
          <nav class="px-4 space-y-5 relative">
            <!-- 新建对话按钮 -->
            <button 
              @click="createNewChat(); toggleSidebar()"
              class="w-full group flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all duration-500 ease-spring transform hover:scale-[1.02] active:scale-[0.98] overflow-hidden relative btn-glow"
              :class="isDarkMode ? 'text-white shadow-lg shadow-[#8153ff]/20' : 'text-gray-800 shadow-md shadow-[#8153ff]/10'"
            >
              <!-- 按钮背景 -->
              <div class="absolute inset-0 bg-gradient-to-r from-[#8153ff] to-[#93dc24] opacity-90 transition-all duration-500 group-hover:opacity-100 z-0"></div>
              
              <!-- 按钮光效 -->
              <div class="absolute -inset-full h-full w-1/2 z-5 transform -skew-x-12 bg-gradient-to-r from-transparent to-white opacity-40 group-hover:animate-shine"></div>
              
              <font-awesome-icon icon="plus" class="mr-3 relative z-10 text-white transition-transform duration-500 ease-spring transform group-hover:rotate-90 group-hover:scale-110" />
              <span class="relative z-10 text-white">新建对话</span>
            </button>
            
            <!-- 选择智能体按钮 -->
            <button 
              @click="showAgentSelector = true; toggleSidebar()"
              class="w-full group flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all duration-500 ease-spring transform hover:scale-[1.02] active:scale-[0.98] overflow-hidden relative btn-glow"
              :class="isDarkMode ? 'text-white shadow-lg shadow-[#8153ff]/20' : 'text-gray-800 shadow-md shadow-[#8153ff]/10'"
            >
              <!-- 按钮背景 -->
              <div class="absolute inset-0 bg-gradient-to-r from-purple-500 to-indigo-500 opacity-90 transition-all duration-500 group-hover:opacity-100 z-0"></div>
              
              <!-- 按钮光效 -->
              <div class="absolute -inset-full h-full w-1/2 z-5 transform -skew-x-12 bg-gradient-to-r from-transparent to-white opacity-40 group-hover:animate-shine"></div>
              
              <font-awesome-icon icon="robot" class="mr-3 relative z-10 text-white transition-transform duration-500 ease-spring transform group-hover:scale-110" />
              <span class="relative z-10 text-white">选择智能体</span>
            </button>
            
            <!-- 历史记录标题 -->
            <div class="pt-2 pb-3">
              <div class="flex items-center justify-between px-1">
                <p class="text-xs font-bold uppercase tracking-wider bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent">
                  历史记录
                </p>
                <!-- 清空所有聊天记录按钮 -->
                <button 
                  v-if="chatHistory.length > 0"
                  @click.stop="showClearAllConfirm = true"
                  class="text-xs flex items-center space-x-1 px-2 py-1 rounded-md transition-all duration-300 hover:scale-105 relative overflow-hidden group"
                  :class="isDarkMode ? 'text-red-400 hover:text-white' : 'text-red-500 hover:text-white'"
                >
                  <!-- 按钮hover背景 -->
                  <div class="absolute inset-0 bg-gradient-to-r from-red-500 to-red-600 opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-md"></div>
                  <font-awesome-icon icon="times" class="text-xs relative z-10" />
                  <span class="relative z-10">清空所有聊天</span>
                </button>
              </div>
            </div>
            
            <!-- 聊天历史列表 -->
            <div class="space-y-2.5 max-h-[calc(100vh-230px)] overflow-y-auto pr-1 scrollbar-thin">
              <div
                v-for="(chat, index) in chatHistory" 
                :key="index"
                @click="selectChat(chat.id); toggleSidebar()"
                class="group/chat flex items-center py-3 px-4 text-sm font-medium rounded-xl cursor-pointer transition-all duration-500 ease-spring transform hover:scale-[1.02] active:scale-[0.98] relative chat-card stagger-item"
                :class="[
                  currentChatId === chat.id 
                    ? (isDarkMode 
                        ? 'bg-gradient-to-r from-[#8153ff]/30 to-[#93dc24]/30 text-white shadow-md shadow-[#8153ff]/20' 
                        : 'bg-gradient-to-r from-[#8153ff]/10 to-[#93dc24]/10 text-gray-800 shadow-sm shadow-[#8153ff]/10') 
                    : (isDarkMode 
                        ? 'text-gray-300 hover:bg-gray-800/60' 
                        : 'text-gray-700 hover:bg-gray-100/80')
                ]"
                :style="`--stagger-delay: ${index * 50}ms`"
              >
                <!-- 聊天记录点击区域 -->
                <div class="flex items-center flex-1 overflow-hidden relative z-10">
                  <div class="mr-3 w-8 h-8 rounded-full flex items-center justify-center transition-all duration-500 transform group-hover/chat:scale-110 overflow-hidden"
                       :class="currentChatId === chat.id 
                         ? 'bg-gradient-to-r from-[#8153ff] to-[#93dc24]' 
                         : (isDarkMode ? 'bg-gray-700' : 'bg-gray-200')"
                  >
                    <font-awesome-icon 
                      :icon="['far', 'comment']" 
                      class="transition-all duration-500" 
                      :class="currentChatId === chat.id ? 'text-white' : (isDarkMode ? 'text-gray-400' : 'text-gray-500')" 
                    />
                  </div>
                  <span class="truncate">{{ chat.title }}</span>
                  
                  <!-- 未选中状态的hover效果 -->
                  <div v-if="currentChatId !== chat.id" 
                       class="absolute inset-0 -z-10 opacity-0 group-hover/chat:opacity-100 transition-opacity duration-500 bg-gradient-to-r"
                       :class="isDarkMode ? 'from-[#8153ff]/10 to-[#93dc24]/5' : 'from-[#8153ff]/5 to-[#93dc24]/5'"
                  ></div>
                </div>
                
                <!-- 删除按钮 - 修改为始终可见 -->
                <button
                  @click.stop="confirmDeleteChat(chat.id)"
                  class="p-1.5 rounded-full transition-all duration-300 transform hover:scale-110 hover:rotate-90 relative z-10 group/delete"
                  :class="isDarkMode ? 'hover:bg-red-500/20 text-gray-400 hover:text-red-400' : 'hover:bg-red-50 text-gray-400 hover:text-red-500'"
                >
                  <font-awesome-icon icon="times" class="text-xs transition-transform duration-300" />
                </button>
                
                <!-- 删除确认遮罩 -->
                <div 
                  v-if="chatToDelete === chat.id"
                  class="absolute inset-0 bg-opacity-95 flex items-center justify-between px-4 rounded-xl z-20 animate-fade-in backdrop-blur-sm"
                  :class="isDarkMode ? 'bg-gray-900' : 'bg-white'"
                  @click.stop
                >
                  <span class="text-xs font-medium" 
                        :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'">
                    确认删除?
                  </span>
                  <div class="flex space-x-3">
                    <button 
                      @click="chatToDelete = null"
                      class="p-1.5 rounded-full transition-all duration-300 transform hover:scale-110 hover:rotate-90"
                      :class="isDarkMode ? 'hover:bg-gray-700 text-gray-400' : 'hover:bg-gray-100 text-gray-500'"
                    >
                      <font-awesome-icon icon="times" />
                    </button>
                    <button 
                      @click="deleteChat(chat.id)"
                      class="p-1.5 rounded-full transition-all duration-300 transform hover:scale-110 bg-gradient-to-r from-red-500 to-red-600 text-white"
                    >
                      <font-awesome-icon icon="check" />
                    </button>
                  </div>
                </div>
                
                <!-- 选中状态指示条 -->
                <div 
                  class="absolute left-0 top-0 bottom-0 w-1.5 rounded-full transition-all duration-500 transform origin-left"
                  :class="[
                    currentChatId === chat.id 
                      ? 'bg-gradient-to-b from-[#8153ff] to-[#93dc24] scale-y-100' 
                      : 'scale-y-0'
                  ]"
                ></div>
              </div>
            </div>
          </nav>
        </div>
        
        <!-- 底部用户信息 -->
        <div class="flex-shrink-0 flex p-4 relative z-10 border-t transition-all duration-500" 
             :class="isDarkMode ? 'border-gray-800' : 'border-gray-200'">
          <div class="flex items-center w-full">
            <div class="relative group">
              <div class="w-10 h-10 rounded-full overflow-hidden bg-gradient-to-r from-[#8153ff] to-[#93dc24] flex items-center justify-center text-white shadow-lg transform transition-transform duration-500 group-hover:scale-110 relative z-10">
                <font-awesome-icon icon="user" />
              </div>
              <!-- 发光效果 -->
              <div class="absolute inset-0 bg-[#8153ff] rounded-full blur-md opacity-30 group-hover:opacity-60 transition-opacity duration-500 -z-10"></div>
            </div>
            <div class="ml-3 flex-1">
              <p class="text-sm font-medium transition-all duration-300" 
                 :class="isDarkMode ? 'text-white' : 'text-gray-800'">
                {{ userStore.user?.username || '用户' }}
              </p>
             
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 - 聊天界面 -->
    <div class="flex-1 flex flex-col overflow-auto transition-all duration-500" ref="contentContainer">
      <!-- 聊天消息区域 -->
      <div 
        ref="messagesContainer"
        class="flex-1 overflow-y-auto px-4 py-5 space-y-4 scrollbar-thin messages-container messages-spacing relative"
        @scroll="checkScroll"
      >
        <!-- 无聊天记录时的欢迎界面 -->
        <div v-if="!currentMessages.length" class="flex flex-col h-full">
          <!-- 问候语 -->
          <div class="mb-6 animate-fade-in-up" style="--delay: 300ms;">
            <h1 class="text-xl font-bold" :class="isDarkMode ? 'text-gray-100' : 'text-gray-800'">Hi, {{ greeting }}!</h1>
            <p class="text-sm" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">欢迎使用黄昆牌AI智能助手，共同探索知识的边界</p>
          </div>
          
          <!-- 智能体选择卡片 -->
          <div 
            @click="showAgentSelector = true"
            class="relative flex items-center p-4 rounded-xl cursor-pointer overflow-hidden border transition-all duration-700 ease-spring transform hover:scale-[1.02] active:scale-[0.98] animate-fade-in-up shadow-sm hover:shadow-md model-card"
            :class="isDarkMode ? 'border-[#8153ff]/30 bg-[#8153ff]/10' : 'border-[#8153ff]/20 bg-[#8153ff]/5'"
            style="--delay: 500ms;"
          >
            <div class="flex-1 z-10 relative">
              <h2 class="font-semibold" :class="isDarkMode ? 'text-white' : 'text-gray-800'">选择智能体</h2>
              <p class="text-sm" :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">选择预设智能体或创建自定义智能体</p>
            </div>
            <div class="w-12 h-12 rounded-full overflow-hidden ml-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] flex items-center justify-center transform transition-transform duration-500 hover:scale-110 hover:rotate-12 z-10">
              <font-awesome-icon icon="robot" class="text-white" size="lg" />
            </div>
            <!-- 背景装饰元素 -->
            <div class="absolute -right-2 -bottom-2 w-16 h-16 rounded-full bg-[#8153ff] opacity-20 transform transition-transform duration-700"></div>
            <div class="absolute -left-2 -top-2 w-10 h-10 rounded-full bg-[#93dc24] opacity-20 transform transition-transform duration-700"></div>
          </div>
          
          <!-- 模型选择卡片 -->
          <div class="grid gap-4 mt-4">
            <!-- MiniMax-Text-01 卡片 -->
            <div 
              @click="selectModel(miniMaxService.MODELS.MINIMAX_TEXT_01)"
              class="relative flex items-center p-4 rounded-xl cursor-pointer overflow-hidden border transition-all duration-700 ease-spring transform hover:scale-[1.02] active:scale-[0.98] animate-fade-in-up shadow-sm hover:shadow-md model-card"
              :class="[
                currentModel === miniMaxService.MODELS.MINIMAX_TEXT_01 
                  ? (isDarkMode ? 'border-orange-500 ring-2 ring-orange-400' : 'border-orange-300 ring-2 ring-orange-200') 
                  : 'border-transparent hover:border-orange-200',
                isDarkMode ? 'bg-orange-900/20' : 'bg-orange-50'
              ]"
              style="--delay: 600ms;"
            >
              <div class="flex-1 z-10 relative">
                <h2 class="font-semibold" :class="isDarkMode ? 'text-white' : 'text-gray-800'">MiniMax-Text-01</h2>
                <p class="text-sm" :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">超长上下文，通用型大模型，支持多种功能扩展</p>
              </div>
              <div class="absolute right-0 top-0 bottom-0 w-24 h-full transform transition-all duration-500 group-hover:scale-105">
                <div class="w-full h-full relative overflow-hidden bg-gradient-to-r from-red-400 to-red-500 rounded-r-xl rounded-l-3xl">
                  <div class="absolute inset-0 rounded-l-full transform -translate-x-1/3 bg-red-300 opacity-80 transition-transform duration-500 hover:translate-x-0"></div>
                  <div class="absolute inset-0 rounded-l-full transform -translate-x-2/3 bg-red-200 opacity-80 transition-transform duration-700 hover:translate-x-1/3"></div>
                  <div class="absolute inset-0 flex items-center justify-center text-white">
                    <p class="text-xs transform rotate-90 font-bold tracking-wide transition-transform duration-500 hover:scale-110">MiniMax<br/>Text-01</p>
                  </div>
                </div>
              </div>
              <!-- 背景装饰元素 -->
              <div class="absolute -right-2 -bottom-2 w-12 h-12 rounded-full bg-red-200 opacity-30 transform transition-transform duration-700"></div>
              <div class="absolute -left-2 -top-2 w-8 h-8 rounded-full bg-orange-300 opacity-20 transform transition-transform duration-700"></div>
            </div>
            
            <!-- Abab 6.5s 卡片 -->
            <div 
              @click="selectModel(miniMaxService.MODELS.ABAB_6_5S_CHAT)"
              class="relative flex items-center p-4 rounded-xl cursor-pointer overflow-hidden border transition-all duration-500 ease-in-out transform hover:scale-[1.02] active:scale-[0.98] animate-fade-in-up shadow-sm hover:shadow-md"
              :class="[
                currentModel === miniMaxService.MODELS.ABAB_6_5S_CHAT 
                  ? (isDarkMode ? 'border-blue-500 ring-2 ring-blue-400' : 'border-blue-300 ring-2 ring-blue-200') 
                  : 'border-transparent hover:border-blue-200',
                isDarkMode ? 'bg-blue-900/20' : 'bg-blue-50'
              ]"
              style="--delay: 700ms;"
            >
              <div class="flex-1 z-10 relative">
                <h2 class="font-semibold" :class="isDarkMode ? 'text-white' : 'text-gray-800'">abab6.5s-chat</h2>
                <p class="text-sm" :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">高效通用模型，性能均衡</p>
              </div>
              <div class="w-12 h-12 rounded-full overflow-hidden ml-2 bg-blue-200 flex items-center justify-center transform transition-transform duration-500 hover:scale-110 hover:rotate-12 z-10">
                <font-awesome-icon icon="bolt" class="text-blue-600" size="lg" />
              </div>
              <!-- 背景装饰元素 -->
              <div class="absolute -right-2 -bottom-2 w-16 h-16 rounded-full bg-blue-200 opacity-30 transform transition-transform duration-700"></div>
              <div class="absolute -left-2 -top-2 w-10 h-10 rounded-full bg-indigo-300 opacity-20 transform transition-transform duration-700"></div>
            </div>
            
            <!-- DeepSeek-R1 卡片 -->
            <div 
              @click="selectModel(miniMaxService.MODELS.DEEPSEEK_R1)"
              class="flex items-center p-4 rounded-xl cursor-pointer transition-all duration-500 ease-in-out transform hover:scale-[1.02] active:scale-[0.98] animate-fade-in-up shadow-sm hover:shadow-md relative overflow-hidden"
              :class="[
                currentModel === miniMaxService.MODELS.DEEPSEEK_R1 
                  ? (isDarkMode ? 'border border-emerald-500 ring-2 ring-emerald-400' : 'border border-emerald-300 ring-2 ring-emerald-200') 
                  : (isDarkMode ? 'border border-transparent hover:border-emerald-700/40' : 'border border-transparent hover:border-emerald-300'),
                isDarkMode ? 'bg-gray-800 shadow-gray-900' : 'bg-white shadow-sm'
              ]"
              style="--delay: 800ms;"
            >
              <div class="w-10 h-10 rounded-full bg-gradient-to-r from-emerald-500 to-teal-500 flex items-center justify-center text-white mr-4 shadow-md transform transition-transform duration-500 hover:scale-110 z-10">
                <font-awesome-icon icon="brain" />
              </div>
              <div class="flex-1 z-10">
                <h2 class="font-semibold" :class="isDarkMode ? 'text-white' : 'text-gray-800'">DeepSeek-R1满血版</h2>
                <p class="text-sm" :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">推理能力强，支持思考链可视化</p>
              </div>
              <!-- 背景装饰元素 -->
              <div class="absolute -right-2 -bottom-2 w-20 h-20 rounded-full bg-teal-200 opacity-20 transform transition-transform duration-700"></div>
              <div class="absolute -left-2 -top-2 w-12 h-12 rounded-full bg-emerald-300 opacity-10 transform transition-transform duration-700"></div>
            </div>
          </div>
        </div>
        
        <!-- 聊天消息 -->
        <template v-else>
          <ChatMessage 
            v-for="(message, index) in currentMessages" 
            :key="index"
            :message="message"
            :dark-mode="isDarkMode"
          />
          
          <!-- 打字中提示 -->
          <div 
            v-if="isTyping" 
            class="flex justify-start max-w-3xl mx-auto animate-slide-in-up"
          >
            <div 
              class="rounded-xl px-4 py-3 shadow-md transition-all duration-500 transform hover:scale-[1.02] relative overflow-hidden group typing-indicator"
              :class="isDarkMode ? 'bg-gray-800/90' : 'bg-white/90'"
            >
              <!-- 背景装饰元素 -->
              <div class="absolute inset-0 bg-gradient-to-r from-[#8153ff]/5 to-[#93dc24]/5 opacity-50 group-hover:opacity-80 transition-opacity duration-500"></div>
              <div class="absolute -bottom-1 -right-1 w-12 h-12 rounded-full bg-[#8153ff]/10 blur-md"></div>
              <div class="absolute -top-2 -left-2 w-10 h-10 rounded-full bg-[#93dc24]/10 blur-md"></div>
              
              <div class="flex items-center space-x-2 relative z-10">
                <div class="relative w-6 h-6">
                  <div class="absolute inset-0 bg-gradient-to-r from-[#8153ff] to-[#93dc24] rounded-full opacity-20 animate-ping-slow"></div>
                  <div class="absolute inset-0 flex items-center justify-center">
                    <div class="typing-animation">
                      <span class="dot" style="--delay: 0ms"></span>
                      <span class="dot" style="--delay: 150ms"></span>
                      <span class="dot" style="--delay: 300ms"></span>
                    </div>
                  </div>
                </div>
                
                <span class="text-xs font-medium transition-all duration-500 opacity-80 group-hover:opacity-100" 
                      :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">AI思考中...</span>
              </div>
              
              <!-- 闪光效果 -->
              <div class="absolute -inset-full h-full w-1/4 z-5 transform -skew-x-12 bg-gradient-to-r from-transparent via-white to-transparent opacity-20 group-hover:animate-shine-slow"></div>
            </div>
          </div>
        </template>
        
        <!-- 滚动到底部按钮 -->
        <div 
          v-if="showScrollButton && currentMessages.length > 0"
          class="fixed bottom-48 right-8 z-50 transition-all duration-500 ease-spring transform"
          :class="showScrollButton ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-10 pointer-events-none'"
        >
          <button 
            @click="scrollToBottom"
            class="w-10 h-10 bg-gradient-to-r from-blue-500 to-indigo-600 rounded-full flex items-center justify-center text-white shadow-lg transition-all duration-500 ease-spring transform hover:scale-110 active:scale-95 scroll-pulse group"
            :class="isDarkMode ? 'hover:from-blue-600 hover:to-indigo-700' : ''"
          >
            <font-awesome-icon icon="chevron-down" class="transition-transform duration-500 ease-spring group-hover:translate-y-0.5" />
          </button>
        </div>
      </div>
      
      <!-- 输入框和操作区域 -->
      <div class="p-4 border-t transition-all duration-500 relative overflow-hidden" 
           :class="isDarkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'">
        <!-- 背景装饰元素 -->
        <div class="absolute -right-20 -bottom-14 w-56 h-56 rounded-full bg-[#8153ff]/5 blur-3xl"></div>
        <div class="absolute -left-10 bottom-0 w-28 h-28 rounded-full bg-[#93dc24]/5 blur-2xl"></div>
        
        <div class="relative mb-2 z-10">
          <!-- 模型选择器 -->
          <div class="flex items-center justify-between mb-4 mt-1">
            <div class="flex items-center space-x-2 relative group/select">
              <label class="text-sm font-medium transition-all duration-500 bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent">当前模型:</label>
              <div class="relative">
                <!-- 模型选择下拉菜单 -->
                <select 
                  v-model="currentModel"
                  class="text-sm rounded-xl pr-8 pl-3 py-2 appearance-none bg-transparent border-0 transition-all duration-500 relative z-10 cursor-pointer"
                  :class="isDarkMode 
                    ? 'text-white hover:text-gray-100' 
                    : 'text-gray-800 hover:text-gray-900'"
                  :style="isDarkMode ? 'color-scheme: dark;' : 'color-scheme: light;'"
                >
                  <option :value="miniMaxService.MODELS.MINIMAX_TEXT_01" :style="isDarkMode ? 'background-color: #1F2937; color: white;' : ''">MiniMax-Text-01</option>
                  <option :value="miniMaxService.MODELS.ABAB_6_5S_CHAT" :style="isDarkMode ? 'background-color: #1F2937; color: white;' : ''">abab6.5s-chat</option>
                  <option :value="miniMaxService.MODELS.DEEPSEEK_R1" :style="isDarkMode ? 'background-color: #1F2937; color: white;' : ''">DeepSeek-R1</option>
                </select>
                
                <!-- 背景装饰和交互效果 -->
                <div 
                  class="absolute inset-0 rounded-xl transition-all duration-500 transform origin-center group-hover/select:scale-[1.05] overflow-hidden"
                  :class="isDarkMode 
                    ? 'bg-gray-800/80 group-hover/select:bg-gray-700/80 border border-[#8153ff]/20 group-hover/select:border-[#8153ff]/40' 
                    : 'bg-gray-100/80 group-hover/select:bg-gray-50/80 border border-[#8153ff]/10 group-hover/select:border-[#8153ff]/30'"
                >
                  <!-- 背景悬停渐变效果 -->
                  <div class="absolute inset-0 bg-gradient-to-r from-[#8153ff]/10 to-[#93dc24]/10 opacity-0 group-hover/select:opacity-100 transition-all duration-700"></div>
                  
                  <!-- 内部闪光效果 -->
                  <div class="absolute -inset-full h-full w-1/3 z-5 transform -skew-x-12 bg-gradient-to-r from-transparent via-white to-transparent opacity-0 group-hover/select:opacity-20 group-hover/select:animate-shine-slow"></div>
                </div>
                
                <!-- 选中状态指示 -->
                <div class="absolute left-0 top-1/2 w-0 h-5 group-hover/select:w-1 -translate-y-1/2 rounded-r-full bg-gradient-to-b from-[#8153ff] to-[#93dc24] opacity-0 group-hover/select:opacity-70 transition-all duration-500"></div>
                
                <!-- 右侧下拉箭头图标 -->
                <div class="absolute right-2 top-1/2 transform -translate-y-1/2 pointer-events-none z-10 transition-transform duration-500 group-hover/select:translate-x-0.5">
                  <font-awesome-icon icon="chevron-down" class="text-xs transition-all duration-500 ease-spring transform origin-center group-hover/select:rotate-180" 
                                    :class="isDarkMode ? 'text-[#8153ff]/70 group-hover/select:text-[#8153ff]' : 'text-[#8153ff]/60 group-hover/select:text-[#8153ff]'" />
                </div>
                
                <!-- 悬停时的微光效果 -->
                <div class="absolute -inset-0.5 rounded-xl opacity-0 group-hover/select:opacity-50 transition-all duration-700 blur-md -z-10"
                    :class="isDarkMode 
                      ? 'bg-gradient-to-r from-[#8153ff]/20 to-[#93dc24]/20' 
                      : 'bg-gradient-to-r from-[#8153ff]/10 to-[#93dc24]/10'">
                </div>
              </div>
            </div>
            
            <div class="flex items-center space-x-3">
              <!-- 选择智能体按钮 -->
              <button 
                @click="showAgentSelector = true"
                class="text-sm flex items-center rounded-xl px-3 py-2 transition-all duration-500 group/agent relative overflow-hidden transform hover:scale-105 active:scale-95 btn-bounce"
                :class="isDarkMode 
                  ? 'text-white bg-gray-800/60 hover:bg-gray-700/60 shadow-md shadow-[#8153ff]/10' 
                  : 'text-gray-700 bg-gray-100/60 hover:bg-gray-50/60 shadow-sm shadow-[#8153ff]/5'"
              >
                <!-- 按钮背景 -->
                <div class="absolute inset-0 border border-[#8153ff]/20 rounded-xl transition-all duration-500 group-hover/agent:border-[#8153ff]/50"></div>
                
                <!-- 背景渐变效果 -->
                <div class="absolute inset-0 bg-gradient-to-r from-[#8153ff]/10 to-[#93dc24]/10 rounded-xl opacity-0 group-hover/agent:opacity-100 transition-all duration-500"></div>
                
                <!-- 闪光效果 -->
                <div class="absolute -inset-full h-full w-1/4 z-5 transform -skew-x-12 bg-gradient-to-r from-transparent via-white to-transparent opacity-20 group-hover/agent:animate-shine-slow"></div>
                
                <font-awesome-icon icon="robot" class="mr-1.5 text-xs transition-all duration-500 ease-spring group-hover/agent:scale-110 text-[#8153ff]" />
                <span class="relative z-10 bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent font-medium">智能体</span>
              </button>
              
              <!-- 新对话按钮 -->
              <button 
                @click="createNewChat"
                class="text-sm flex items-center rounded-xl px-3 py-2 transition-all duration-500 group/new relative overflow-hidden transform hover:scale-105 active:scale-95 btn-bounce"
                :class="isDarkMode 
                  ? 'text-white bg-gray-800/60 hover:bg-gray-700/60 shadow-md shadow-[#8153ff]/10' 
                  : 'text-gray-700 bg-gray-100/60 hover:bg-gray-50/60 shadow-sm shadow-[#8153ff]/5'"
              >
                <!-- 按钮背景 -->
                <div class="absolute inset-0 border border-[#8153ff]/20 rounded-xl transition-all duration-500 group-hover/new:border-[#8153ff]/50"></div>
                
                <!-- 背景渐变效果 -->
                <div class="absolute inset-0 bg-gradient-to-r from-[#8153ff]/10 to-[#93dc24]/10 rounded-xl opacity-0 group-hover/new:opacity-100 transition-all duration-500"></div>
                
                <!-- 闪光效果 -->
                <div class="absolute -inset-full h-full w-1/4 z-5 transform -skew-x-12 bg-gradient-to-r from-transparent via-white to-transparent opacity-20 group-hover/new:animate-shine-slow"></div>
                
                <font-awesome-icon icon="plus" class="mr-1.5 text-xs transition-all duration-500 ease-spring group-hover/new:scale-110 group-hover/new:rotate-90 text-[#8153ff]" />
                <span class="relative z-10 bg-gradient-to-r from-[#8153ff] to-[#93dc24] bg-clip-text text-transparent font-medium">新对话</span>
              </button>
            </div>
          </div>
          
          <!-- 消息输入区域 -->
          <div class="relative mb-2 mt-2 overflow-hidden transition-all duration-500 group/input animate-fade-in-up input-focus-effect" :class="inputFocused ? 'focused' : ''" style="--delay: 400ms;">
            <div 
              class="absolute inset-0 rounded-2xl transition-all duration-700"
              :class="isDarkMode 
                ? 'bg-gradient-to-tr from-gray-700/50 to-gray-800/50 shadow-inner group-hover/input:from-gray-700/70 group-hover/input:to-gray-800/70' 
                : 'bg-gradient-to-tr from-gray-100/70 to-white/70 shadow-sm group-hover/input:from-gray-50 group-hover/input:to-white'"
            ></div>
            <div 
              class="absolute inset-0 rounded-2xl opacity-0 transition-opacity duration-1000"
              :class="inputFocused 
                ? 'opacity-100' 
                : 'opacity-0'"
            >
              <!-- 焦点状态背景 -->
              <div 
                class="absolute inset-0 rounded-2xl bg-gradient-to-r blur-xl opacity-10 transition-all duration-700 animate-pulse"
                :class="isDarkMode 
                  ? 'from-[#8153ff]/20 to-[#93dc24]/20' 
                  : 'from-[#8153ff]/10 to-[#93dc24]/10'"
              ></div>
            </div>
            <textarea 
              v-model="messageInput"
              @keydown.enter.prevent="sendMessage"
              @focus="inputFocused = true"
              @blur="inputFocused = false"
              :disabled="isTyping"
              rows="1"
              class="w-full pr-14 py-4 pl-5 rounded-2xl resize-none transition-all duration-500 bg-transparent relative z-10 focus:outline-none font-app font-size-app input-text"
              :class="[
                isDarkMode 
                  ? 'text-gray-200 placeholder-gray-400 focus:placeholder-gray-500' 
                  : 'text-gray-800 placeholder-gray-400 focus:placeholder-gray-300',
                inputFocused
                  ? (isDarkMode ? 'shadow-[0_0_15px_rgba(129,83,255,0.15)]' : 'shadow-[0_0_20px_rgba(129,83,255,0.1)]')
                  : ''
              ]"
              placeholder="输入消息..."
              ref="textareaRef"
            ></textarea>
            <button 
              @click="sendMessage" 
              :disabled="isTyping || !messageInput.trim()"
              class="absolute right-3 bottom-3 p-3 rounded-xl transition-all duration-500 z-10 overflow-hidden group/btn transform"
              :class="[
                messageInput.trim() 
                  ? 'text-white shadow-md hover:shadow-lg active:shadow-inner hover:scale-105 active:scale-95 send-btn-active' 
                  : (isDarkMode ? 'bg-gray-700 text-gray-400' : 'bg-gray-200 text-gray-400'),
                inputFocused && messageInput.trim() ? 'scale-105' : '',
                isTyping ? 'animate-pulse' : ''
              ]"
            >
              <!-- 发送按钮背景 -->
              <div v-if="messageInput.trim()" class="absolute inset-0 bg-gradient-to-r from-[#8153ff] to-[#93dc24] rounded-xl transition-all duration-500 z-0"></div>
              
              <!-- 按钮光效 -->
              <span class="absolute inset-0 bg-white opacity-0 group-hover/btn:opacity-10 transition-opacity duration-500 rounded-xl"></span>
              <span class="absolute inset-0 bg-gradient-to-r from-[#8153ff]/0 to-[#93dc24]/0 group-hover/btn:from-[#8153ff]/5 group-hover/btn:to-[#93dc24]/5 opacity-0 group-hover/btn:opacity-100 transition-all duration-700 rounded-xl"></span>
              
              <font-awesome-icon 
                :icon="isTyping ? 'spinner' : 'paper-plane'" 
                :spin="isTyping" 
                class="relative z-10 transition-all duration-500 ease-spring group-hover/btn:scale-110 group-active/btn:scale-95" 
              />
            </button>
            
            <!-- 输入框焦点指示线 -->
            <div 
              class="absolute bottom-0 left-0 right-0 h-[2px] transition-all duration-500 transform origin-center"
              :class="inputFocused 
                ? 'scale-x-100 bg-gradient-to-r from-[#8153ff] to-[#93dc24]' 
                : 'scale-x-0 bg-transparent'"
            ></div>
          </div>
          
          <!-- 辅助提示 -->
          <p class="text-xs text-center transition-all duration-500 opacity-70 hover:opacity-100 py-1 animate-fade-in-up" 
             :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'"
             style="--delay: 500ms;">
            {{ currentModel === miniMaxService.MODELS.DEEPSEEK_R1 ? '将显示思考过程和回答内容' : '输入问题并按回车发送' }}
          </p>
        </div>
      </div>
    </div>

    <!-- 清空所有确认对话框 -->
    <div 
      v-if="showClearAllConfirm" 
      class="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 animate-fade-in"
    >
      <div 
        class="p-5 rounded-xl shadow-lg max-w-sm w-full mx-4 border animate-scale-in"
        :class="isDarkMode ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'"
      >
        <h3 class="text-lg font-medium mb-2" :class="isDarkMode ? 'text-white' : 'text-gray-900'">确认清空</h3>
        <p class="mb-4 text-sm" :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">
          确定要删除所有聊天记录吗？此操作无法撤销。
        </p>
        <div class="flex justify-end space-x-3">
          <button 
            @click="showClearAllConfirm = false"
            class="px-3 py-1.5 rounded-lg text-sm transition duration-300 btn-bounce"
            :class="isDarkMode ? 'text-gray-300 hover:bg-gray-700' : 'text-gray-700 hover:bg-gray-100'"
          >
            取消
          </button>
          <button 
            @click="clearAllChats"
            class="px-3 py-1.5 rounded-lg text-sm text-white bg-red-500 hover:bg-red-600 transition duration-300 btn-bounce"
          >
            确认清空
          </button>
        </div>
      </div>
    </div>
    
    <!-- 智能体选择器 -->
    <AgentSelector 
      :show="showAgentSelector" 
      :isDarkMode="isDarkMode"
      @close="showAgentSelector = false"
      @select="handleAgentSelect"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/userStore';
import { toast } from '../services/toastService';
import miniMaxService from '../services/miniMaxService';
import ChatMessage from '../components/ChatMessage.vue';
import { v4 as uuidv4 } from 'uuid';
import UserMenu from '../components/UserMenu.vue';
import AgentSelector from '../components/AgentSelector.vue';

const router = useRouter();
const userStore = useUserStore();

// 暗黑模式状态
const isDarkMode = ref(false);

// 切换暗黑模式
const toggleDarkMode = () => {
  isDarkMode.value = !isDarkMode.value;
  saveThemePreference();
  
  // 切换图标提示信息
  const modeText = isDarkMode.value ? '已切换到暗黑模式' : '已切换到亮色模式';
  toast.info(modeText, 1500);
};

// 保存主题偏好到本地存储
const saveThemePreference = () => {
  localStorage.setItem('darkModePreference', isDarkMode.value.toString());
};

// 从本地存储加载主题偏好
const loadThemePreference = () => {
  const savedPreference = localStorage.getItem('darkModePreference');
  if (savedPreference !== null) {
    isDarkMode.value = savedPreference === 'true';
  } else {
    // 如果没有保存的偏好，尝试使用系统偏好
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    isDarkMode.value = prefersDark;
  }
};

// 侧边栏状态
const sidebarOpen = ref(false);
const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value;
};

// 根据时间获取问候语
const greeting = computed(() => {
  const hour = new Date().getHours();
  if (hour < 6) return '凌晨好';
  if (hour < 9) return '早上好';
  if (hour < 12) return '上午好';
  if (hour < 14) return '中午好';
  if (hour < 18) return '下午好';
  if (hour < 22) return '晚上好';
  return '夜深了';
});

// 聊天状态
const chatHistory = ref([]);
const currentChatId = ref(null);
const currentModel = ref(miniMaxService.MODELS.MINIMAX_TEXT_01);
const messageInput = ref('');
const isTyping = ref(false);
const inputFocused = ref(false);
const messagesContainer = ref(null);
const textareaRef = ref(null);
const contentContainer = ref(null);

// 获取当前聊天的消息
const currentMessages = computed(() => {
  if (!currentChatId.value) return [];
  const chat = chatHistory.value.find(c => c.id === currentChatId.value);
  return chat ? chat.messages : [];
});

// 选择模型
const selectModel = (model) => {
  currentModel.value = model;
  if (!currentChatId.value) {
    createNewChat();
  }
};

// 创建新的聊天
const createNewChat = () => {
  const chatId = uuidv4();
  const newChat = {
    id: chatId,
    title: `新对话`,
    model: currentModel.value,
    lastUpdated: new Date(),
    messages: []
  };
  
  chatHistory.value.unshift(newChat);
  currentChatId.value = chatId;
  
  // 保存到本地存储
  saveChatsToLocalStorage();
};

// 选择聊天
const selectChat = (chatId) => {
  const chat = chatHistory.value.find(c => c.id === chatId);
  if (chat) {
    currentChatId.value = chatId;
    currentModel.value = chat.model; // 同步当前选择的模型
    nextTick().then(scrollToBottom);
  }
};

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim() || isTyping.value) return;
  
  if (!currentChatId.value) {
    createNewChat();
  }
  
  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    content: messageInput.value,
    isUser: true,
    timestamp: new Date()
  };
  
  const currentChat = chatHistory.value.find(c => c.id === currentChatId.value);
  currentChat.messages.push(userMessage);
  currentChat.lastUpdated = new Date();
  
  // 更新标题（如果是第一条消息）
  if (currentChat.messages.length === 1) {
    currentChat.title = messageInput.value.length > 20 
      ? `${messageInput.value.substring(0, 20)}...` 
      : messageInput.value;
  }
  
  // 清空输入框
  messageInput.value = '';
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();
  
  // 显示AI正在输入状态
  isTyping.value = true;
  
  try {
    // 获取系统提示词
    let systemPrompt = '';
    if (currentChat.agent && currentChat.agent.systemPrompt) {
      systemPrompt = currentChat.agent.systemPrompt;
      console.log('使用智能体系统提示:', systemPrompt);
    }
    
    // 准备消息格式，包含系统提示词
    const formattedMessages = miniMaxService.formatMessages(
      currentChat.messages, 
      systemPrompt, 
      currentModel.value
    );
    
    // 根据模型是否为DeepSeek-R1处理不同的响应逻辑
    if (currentModel.value === miniMaxService.MODELS.DEEPSEEK_R1) {
      await handleDeepSeekR1Response(formattedMessages, currentChat);
    } else {
      await handleStandardResponse(formattedMessages, currentChat);
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    
    // 添加错误消息
    currentChat.messages.push({
      id: Date.now(),
      content: `请求出错: ${error.message || '未知错误'}`,
      isUser: false,
      timestamp: new Date()
    });
    
    toast.error('发送消息失败，请重试', 3000);
  } finally {
    isTyping.value = false;
    currentChat.lastUpdated = new Date();
    saveChatsToLocalStorage();
    nextTick().then(scrollToBottom);
  }
};

// 处理DeepSeek-R1模型响应（包含思考链）
const handleDeepSeekR1Response = async (formattedMessages, currentChat) => {
  let reasoningChain = '';
  let responseContent = '';
  let responsePending = false; // 避免过于频繁的UI更新
  let lastUpdateTime = Date.now(); // 上次更新UI的时间
  const updateInterval = 16; // 约60fps，更丝滑的更新频率
  
  // 创建空的AI回复消息
  const aiMessageId = Date.now();
  currentChat.messages.push({
    id: aiMessageId,
    content: '',
    reasoningChain: '',
    isUser: false,
    timestamp: new Date()
  });
  
  // 优化的UI更新函数，降低更新频率
  const smoothUpdate = (aiMessage) => {
    const now = Date.now();
    if (now - lastUpdateTime >= updateInterval || !responsePending) {
      // 保存状态并滚动
      saveChatsToLocalStorage();
      nextTick().then(scrollToBottom);
      lastUpdateTime = now;
      responsePending = false;
    } else {
      // 如果更新太频繁，标记为待更新，但不立即执行
      responsePending = true;
      setTimeout(() => {
        if (responsePending) {
          saveChatsToLocalStorage();
          nextTick().then(scrollToBottom);
          responsePending = false;
          lastUpdateTime = Date.now();
        }
      }, updateInterval);
    }
  };
  
  // 使用流式响应
  await miniMaxService.streamChatCompletion(formattedMessages, currentModel.value, (chunk) => {
    // 查找当前AI消息
    const aiMessage = currentChat.messages.find(msg => msg.id === aiMessageId);
    if (!aiMessage) return;
    
    // 添加调试日志来分析响应内容
    console.log('DeepSeek-R1 chunk:', JSON.stringify(chunk));
    
    // 处理思维链内容 - 只有当chunk包含reasoning_content时才更新
    if (chunk.choices && 
        chunk.choices[0] && 
        chunk.choices[0].delta && 
        chunk.choices[0].delta.reasoning_content) {
      const reasoningContent = chunk.choices[0].delta.reasoning_content;
      reasoningChain += reasoningContent;
      aiMessage.reasoningChain = reasoningChain;
      smoothUpdate(aiMessage);
    }
    
    // 处理正文内容 - 只有当chunk包含content且不是reasoning_content时才更新
    if (chunk.choices && 
        chunk.choices[0] && 
        chunk.choices[0].delta && 
        chunk.choices[0].delta.content) {
      const content = chunk.choices[0].delta.content;
      responseContent += content;
      aiMessage.content = responseContent;
      smoothUpdate(aiMessage);
    }
    
    // 处理完整消息对象
    if (chunk.choices && 
        chunk.choices[0] && 
        chunk.choices[0].message && 
        chunk.choices[0].message.content) {
      responseContent = chunk.choices[0].message.content;
      aiMessage.content = responseContent;
      smoothUpdate(aiMessage);
    }
  });
};

// 处理标准模型响应
const handleStandardResponse = async (formattedMessages, currentChat) => {
  let responseContent = '';
  let responsePending = false; // 避免过于频繁的UI更新
  let lastUpdateTime = Date.now(); // 上次更新UI的时间
  const updateInterval = 16; // 约60fps，更丝滑的更新频率
  
  // 优化的UI更新函数，降低更新频率
  const smoothUpdate = (lastMessage) => {
    const now = Date.now();
    if (now - lastUpdateTime >= updateInterval || !responsePending) {
      // 保存状态并滚动
      saveChatsToLocalStorage();
      nextTick().then(scrollToBottom);
      lastUpdateTime = now;
      responsePending = false;
    } else {
      // 如果更新太频繁，标记为待更新，但不立即执行
      responsePending = true;
      setTimeout(() => {
        if (responsePending) {
          saveChatsToLocalStorage();
          nextTick().then(scrollToBottom);
          responsePending = false;
          lastUpdateTime = Date.now();
        }
      }, updateInterval);
    }
  };
  
  // 使用流式响应
  await miniMaxService.streamChatCompletion(formattedMessages, currentModel.value, (chunk) => {
    // 处理每个数据块
    if (chunk.choices && chunk.choices[0] && chunk.choices[0].delta && chunk.choices[0].delta.content) {
      responseContent += chunk.choices[0].delta.content;
      
      // 更新或创建AI回复消息
      const lastMessage = currentChat.messages[currentChat.messages.length - 1];
      if (!lastMessage.isUser) {
        lastMessage.content = responseContent;
      } else {
        currentChat.messages.push({
          id: Date.now(),
          content: responseContent,
          isUser: false,
          timestamp: new Date()
        });
      }
      
      // 平滑更新UI
      smoothUpdate(lastMessage);
    }
  });
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTo({
      top: messagesContainer.value.scrollHeight,
      behavior: 'smooth'
    });
  }
};

// 检测滚动位置
const checkScroll = () => {
  if (!messagesContainer.value || !currentMessages.value.length) return;
  
  const { scrollTop, scrollHeight, clientHeight } = messagesContainer.value;
  const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;
  
  showScrollButton.value = !isNearBottom;
};

// 自动调整文本框高度
watch(messageInput, () => {
  nextTick(() => {
    const textarea = textareaRef.value;
    if (textarea) {
      textarea.style.height = 'auto';
      textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;
    }
  });
});

// 保存聊天到本地存储
const saveChatsToLocalStorage = () => {
  localStorage.setItem('aiChatHistory', JSON.stringify(chatHistory.value));
};

// 从本地存储加载聊天
const loadChatsFromLocalStorage = () => {
  const savedChats = localStorage.getItem('aiChatHistory');
  if (savedChats) {
    try {
      chatHistory.value = JSON.parse(savedChats);
      
      // 如果有聊天记录，选择最近的一个
      if (chatHistory.value.length > 0) {
        currentChatId.value = chatHistory.value[0].id;
        currentModel.value = chatHistory.value[0].model || miniMaxService.MODELS.MINIMAX_TEXT_01;
      }
    } catch (e) {
      console.error('加载聊天历史失败:', e);
    }
  }
};

// 监听当前聊天变化，更新列表
watch(currentChatId, () => {
  if (currentChatId.value) {
    const index = chatHistory.value.findIndex(c => c.id === currentChatId.value);
    if (index > 0) {
      // 将当前会话移到顶部
      const chat = chatHistory.value.splice(index, 1)[0];
      chatHistory.value.unshift(chat);
      // 保存变更
      saveChatsToLocalStorage();
    }
  }
});

// 滚动按钮状态
const showScrollButton = ref(false);

// 组件挂载时的操作
onMounted(() => {
  // 从本地存储加载主题偏好
  loadThemePreference();
  
  // 从本地存储加载用户设置（字体等）
  loadUserSettings();
  
  // 从本地存储加载聊天记录
  loadChatsFromLocalStorage();
  
  // 初始时聚焦输入框
  if (textareaRef.value) {
    textareaRef.value.focus();
  }
  
  // 监听滚动事件
  if (messagesContainer.value) {
    messagesContainer.value.addEventListener('scroll', checkScroll);
  }
  
  // 检查窗口大小变化时更新滚动状态
  window.addEventListener('resize', () => {
    nextTick().then(checkScroll);
    adjustTextareaHeight();
  });
  
  // 初始化后检查滚动状态
  nextTick().then(() => {
    // 给UI时间渲染
    setTimeout(() => {
      scrollToBottom();
      checkScroll();
    }, 500);
  });
  
  // 默认选择模型
  if (!currentModel.value) {
    currentModel.value = miniMaxService.MODELS.MINIMAX_TEXT_01;
  }
  
  // 检查用户是否已登录，未登录则跳转到登录页
  if (!userStore.isAuthenticated) {
    router.push('/login');
  }
});

// 加载用户设置（字体等）
const loadUserSettings = () => {
  // 尝试从localStorage加载字体设置
  const savedSettings = localStorage.getItem('appSettings');
  if (savedSettings) {
    try {
      const settings = JSON.parse(savedSettings);
      // 应用字体设置到文档
      document.documentElement.style.setProperty('--app-font-family', settings.fontFamily || 'PingFang SC, Microsoft YaHei, sans-serif');
      document.documentElement.style.setProperty('--app-font-size', `${settings.fontSize || 16}px`);
    } catch (error) {
      console.error('加载用户设置失败:', error);
    }
  }
};

// 组件卸载前的清理操作
onBeforeUnmount(() => {
  window.removeEventListener('resize', () => {
    checkScroll();
    adjustTextareaHeight();
  });
  if (messagesContainer.value) {
    messagesContainer.value.removeEventListener('scroll', checkScroll);
  }
});

// 监听消息变化，检查是否需要显示滚动按钮
watch(currentMessages, () => {
  nextTick().then(() => {
    scrollToBottom();
    // 延迟检查以确保UI已完全更新
    setTimeout(() => {
      checkScroll();
    }, 300);
  });
}, { deep: true });

// 监听当前聊天ID变化，滚动到底部
watch(currentChatId, () => {
  nextTick().then(() => {
    scrollToBottom();
    // 延迟检查以确保UI已完全更新
    setTimeout(() => {
      checkScroll();
    }, 300);
  });
});

// 阻止事件冒泡
const stopPropagation = (e) => {
  e.stopPropagation();
};

// 在script setup部分添加新的状态和函数
const chatToDelete = ref(null);
const showClearAllConfirm = ref(false);

// 确认删除单个聊天前设置要删除的聊天ID
const confirmDeleteChat = (chatId) => {
  chatToDelete.value = chatId;
};

// 删除单个聊天记录
const deleteChat = (chatId) => {
  const index = chatHistory.value.findIndex(c => c.id === chatId);
  if (index !== -1) {
    chatHistory.value.splice(index, 1);
    saveChatsToLocalStorage();
    
    // 如果删除的是当前选中的聊天
    if (currentChatId.value === chatId) {
      // 如果还有其他聊天，选择第一个
      if (chatHistory.value.length > 0) {
        currentChatId.value = chatHistory.value[0].id;
        currentModel.value = chatHistory.value[0].model;
      } else {
        // 没有聊天记录时清空当前选择
        currentChatId.value = null;
      }
    }
    
    chatToDelete.value = null;
    toast.success('聊天记录已删除', 1500);
  }
};

// 清空所有聊天记录
const clearAllChats = () => {
  chatHistory.value = [];
  currentChatId.value = null;
  saveChatsToLocalStorage();
  showClearAllConfirm.value = false;
  toast.success('已清空所有聊天记录', 2000);
};

// 调整文本区域高度
const adjustTextareaHeight = () => {
  if (textareaRef.value) {
    textareaRef.value.style.height = 'auto';
    textareaRef.value.style.height = `${Math.min(textareaRef.value.scrollHeight, 150)}px`;
  }
};

// 监听输入变化，自动调整高度
watch(messageInput, () => {
  nextTick().then(adjustTextareaHeight);
});

// 智能体选择器状态
const showAgentSelector = ref(false);

// 处理智能体选择
const handleAgentSelect = (agent) => {
  // 创建新对话并设置为当前智能体
  console.log('智能体选择:', agent);
  
  // 如果已有对话，则使用现有对话，否则创建新对话
  if (!currentChatId.value) {
    createNewChat();
  }
  
  // 获取当前对话
  const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value);
  if (currentChat) {
    // 更新对话标题，如果还没有自定义标题的话
    if (currentChat.title === '新对话') {
      currentChat.title = `与${agent.name}的对话`;
    }
    
    // 保存选择的智能体信息到当前对话
    currentChat.agent = {
      id: agent.id,
      name: agent.name,
      systemPrompt: agent.systemPrompt,
      description: agent.description || ''
    };
    
    // 检查是否需要添加系统消息和欢迎消息
    const hasMessages = currentChat.messages && currentChat.messages.length > 0;
    
    if (!hasMessages) {
      // 添加隐藏的系统消息(仅存储，不显示在UI上)
      const systemMessage = {
        id: uuidv4(),
        role: 'system',
        content: agent.systemPrompt,
        timestamp: new Date().toISOString(),
        isHidden: true
      };
      
      currentChat.messages.push(systemMessage);
      
      // 添加欢迎消息
      const welcomeMessage = {
        id: uuidv4(),
        isUser: false,
        content: `你好！我是${agent.name}${agent.description ? '，' + agent.description : ''}。有什么我可以帮助你的吗？`,
        timestamp: new Date().toISOString()
      };
      
      currentChat.messages.push(welcomeMessage);
    } else {
      // 如果对话中已有消息，显示通知告知用户智能体已切换
      const notificationMessage = {
        id: uuidv4(),
        isUser: false,
        content: `智能体已切换为"${agent.name}"。现在的对话将基于新智能体的特性进行。`,
        timestamp: new Date().toISOString(),
        isSystemNotification: true
      };
      
      currentChat.messages.push(notificationMessage);
    }
    
    // 保存聊天记录到本地存储
    saveChatsToLocalStorage();
    
    // 滚动到底部
    nextTick().then(scrollToBottom);
    
    // 显示成功消息
    toast.success(`已选择智能体: ${agent.name}`, 2000);
  }
  
  showAgentSelector.value = false;
};
</script>

<style scoped>
/* 自定义滚动条 */
.scrollbar-thin::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

.scrollbar-thin::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 3px;
}

.scrollbar-thin::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.3);
  border-radius: 9999px;
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.scrollbar-thin:hover::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.5);
}

.scrollbar-thin::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.7);
}

/* 文本输入框自动调整高度 */
textarea {
  min-height: 48px;
  max-height: 120px;
  overflow-y: auto;
  transition: height 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), 
              background-color 0.3s ease, 
              box-shadow 0.5s ease;
}

/* 打字中动画效果 */
.typing-dot {
  opacity: 0.4;
  animation: typing-animation 1.5s cubic-bezier(0.45, 0.05, 0.55, 0.95) infinite;
  animation-delay: var(--delay);
  transform-origin: center bottom;
}

.typing-dot-light {
  background-color: rgba(107, 114, 128, 0.8);
  box-shadow: 0 0 5px rgba(107, 114, 128, 0.3);
}

.typing-dot-dark {
  background-color: rgba(156, 163, 175, 0.8);
  box-shadow: 0 0 5px rgba(156, 163, 175, 0.3);
}

@keyframes typing-animation {
  0% {
    opacity: 0.4;
    transform: translateY(0) scale(1);
  }
  50% {
    opacity: 1;
    transform: translateY(-4px) scale(1.3);
  }
  100% {
    opacity: 0.4;
    transform: translateY(0) scale(1);
  }
}

/* 渐变动画 */
.animate-gradient-x {
  background-size: 200% 200%;
  animation: gradient-x 6s ease infinite;
}

@keyframes gradient-x {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* 菜单出现动画 */
.animate-menu-appear {
  animation: menu-appear 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  transform-origin: top right;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 
              0 8px 10px -6px rgba(0, 0, 0, 0.1);
}

@keyframes menu-appear {
  0% {
    opacity: 0;
    transform: scale(0.9) translateY(-10px);
  }
  60% {
    transform: scale(1.03) translateY(2px);
  }
  100% {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

/* 淡入上升动画 */
.animate-fade-in-up {
  opacity: 0;
  transform: translateY(15px);
  animation: fade-in-up 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  animation-delay: var(--delay, 0ms);
}

@keyframes fade-in-up {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滑入上升动画 */
.animate-slide-in-up {
  animation: slide-in-up 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  will-change: transform, opacity;
}

@keyframes slide-in-up {
  0% {
    opacity: 0;
    transform: translateY(12px) scale(0.96);
  }
  70% {
    transform: translateY(-3px) scale(1.02);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 弹性缓动 */
.ease-spring {
  transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 聊天消息区域的滚动效果 */
.messages-container {
  scroll-behavior: smooth;
  scroll-padding: 1rem;
  overscroll-behavior: contain;
}

/* 侧边栏动画 */
.sidebar-enter {
  animation: sidebar-enter 0.8s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  box-shadow: 0 0 15px rgba(129, 83, 255, 0.15);
}

@keyframes sidebar-enter {
  0% {
    transform: translateX(-100%);
    opacity: 0.5;
    box-shadow: 0 0 0 rgba(129, 83, 255, 0);
  }
  60% {
    transform: translateX(3%);
  }
  80% {
    box-shadow: 0 0 20px rgba(129, 83, 255, 0.3);
  }
  100% {
    transform: translateX(0);
    opacity: 1;
    box-shadow: 0 0 15px rgba(129, 83, 255, 0.15);
  }
}

/* 按钮通用过渡效果 */
.btn-bounce {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.btn-bounce:hover {
  transform: scale(1.05);
}

.btn-bounce:active {
  transform: scale(0.95);
}

/* 聊天卡片悬浮效果 */
.chat-card {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  will-change: transform, box-shadow, background-color;
}

.chat-card:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 10px 20px rgba(129, 83, 255, 0.1);
}

.chat-card:active {
  transform: translateY(1px) scale(0.98);
}

/* 输入框焦点效果 */
.input-focus-effect {
  position: relative;
  overflow: hidden;
}

.input-focus-effect::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, #3b82f6, #6366f1);
  transition: width 0.5s cubic-bezier(0.34, 1.56, 0.64, 1), left 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
  border-radius: 2px;
}

.input-focus-effect.focused::after {
  width: 100%;
  left: 0;
}

/* 模型选择卡片悬浮效果 */
.model-card {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.model-card:hover {
  transform: translateY(-3px) scale(1.03);
  box-shadow: 0 15px 30px rgba(0,0,0,0.1), 0 5px 15px rgba(0,0,0,0.07);
}

.model-card:active {
  transform: translateY(1px) scale(0.98);
}

/* 发送按钮悬浮态 */
.send-btn-hover {
  box-shadow: 0 0 15px rgba(59, 130, 246, 0.5);
  transform: scale(1.1);
}

/* 聊天消息列表间距动画 */
.messages-spacing {
  transition: margin 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 图标旋转动画 */
.icon-rotate {
  transition: transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.icon-rotate:hover {
  transform: rotate(15deg);
}

/* 用户菜单按钮弹跳效果 */
.user-menu-btn {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.user-menu-btn:hover {
  transform: scale(1.1);
}

.user-menu-btn:active {
  transform: scale(0.9);
}

/* 主题切换动画 */
.theme-switch {
  position: relative;
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-style: preserve-3d;
  perspective: 500px;
}

.theme-switch-inner {
  transition: transform 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.theme-switch:hover .theme-switch-inner {
  transform: rotateY(180deg);
}

/* 滚动到底部按钮动画 */
@keyframes pulse-ring {
  0% {
    transform: scale(0.8);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.4;
  }
  100% {
    transform: scale(0.8);
    opacity: 0.8;
  }
}

.scroll-pulse::before {
  content: '';
  position: absolute;
  inset: -4px;
  border-radius: inherit;
  background: rgba(59, 130, 246, 0.3);
  animation: pulse-ring 2s infinite;
  z-index: -1;
}

/* 流畅的内容加载动画 */
.content-enter {
  animation: content-enter 0.8s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes content-enter {
  0% {
    opacity: 0;
    transform: translateY(15px) scale(0.98);
    filter: blur(5px);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
    filter: blur(0);
  }
}

/* 模型卡片内光晕效果 */
.model-card::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(
    circle,
    rgba(255, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0) 70%
  );
  opacity: 0;
  transition: opacity 1s cubic-bezier(0.34, 1.56, 0.64, 1);
  pointer-events: none;
  mix-blend-mode: overlay;
}

.model-card:hover::after {
  opacity: 1;
}

/* 按钮点击波纹效果 */
.btn-ripple {
  position: relative;
  overflow: hidden;
}

.btn-ripple::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 0;
  border-radius: 100%;
  transform: scale(1) translate(-50%, -50%);
  transform-origin: 50% 50%;
}

.btn-ripple:active::after {
  animation: ripple 0.6s ease-out;
}

@keyframes ripple {
  0% {
    transform: scale(0) translate(-50%, -50%);
    opacity: 0.5;
  }
  100% {
    transform: scale(20) translate(-50%, -50%);
    opacity: 0;
  }
}

/* 3D悬浮效果 */
.hover-3d {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-style: preserve-3d;
  perspective: 1000px;
}

.hover-3d:hover {
  transform: rotateX(5deg) rotateY(5deg) scale(1.05);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

/* 消息加载时流畅过渡效果 */
.message-transition-group-enter-active,
.message-transition-group-leave-active {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.message-transition-group-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.message-transition-group-leave-to {
  opacity: 0;
  transform: translateY(-20px) scale(0.95);
}

/* 聊天页面平滑切换效果 */
.chat-view-enter-active,
.chat-view-leave-active {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.chat-view-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.chat-view-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 动画延迟序列 */
.stagger-item {
  opacity: 0;
  animation: stagger-fade-in 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  animation-delay: var(--stagger-delay, 0ms);
}

@keyframes stagger-fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 闪光扫过效果 */
@keyframes shine {
  0% {
    left: -100%;
    opacity: 0;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    left: 100%;
    opacity: 0;
  }
}

.animate-shine {
  animation: shine 1.2s ease-in-out;
}

/* 慢速脉冲动画 */
@keyframes pulse-slow {
  0% {
    opacity: 0.3;
    transform: scale(0.97);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.03);
  }
  100% {
    opacity: 0.3;
    transform: scale(0.97);
  }
}

.animate-pulse-slow {
  animation: pulse-slow 4s ease-in-out infinite;
}

/* 删除确认动画 */
.animate-fade-in {
  animation: fade-in 0.3s ease forwards;
}

@keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.animate-scale-in {
  animation: scale-in 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}

@keyframes scale-in {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

/* 对话按钮特效 */
@keyframes button-glow {
  0% {
    box-shadow: 0 0 5px rgba(129, 83, 255, 0.3);
  }
  50% {
    box-shadow: 0 0 15px rgba(129, 83, 255, 0.5), 0 0 30px rgba(147, 220, 36, 0.3);
  }
  100% {
    box-shadow: 0 0 5px rgba(129, 83, 255, 0.3);
  }
}

.btn-glow {
  animation: button-glow 3s infinite ease-in-out;
}

/* 打字提示新样式 */
.typing-animation {
  display: flex;
  align-items: center;
  column-gap: 4px;
}

.typing-animation .dot {
  display: block;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: white;
  box-shadow: 0 0 5px rgba(129, 83, 255, 0.7);
  animation: jump 1.5s cubic-bezier(0.45, 0.05, 0.55, 0.95) infinite;
  animation-delay: var(--delay, 0ms);
  background-image: linear-gradient(to right, #8153ff, #93dc24);
}

@keyframes jump {
  0%, 100% {
    transform: translateY(0) scale(1);
    opacity: 0.7;
  }
  50% {
    transform: translateY(-8px) scale(1.2);
    opacity: 1;
  }
}

/* 缓慢闪光效果 */
@keyframes shine-slow {
  0% {
    left: -100%;
    opacity: 0;
  }
  50% {
    opacity: 0.3;
  }
  100% {
    left: 100%;
    opacity: 0;
  }
}

.animate-shine-slow {
  animation: shine-slow 3s ease-in-out infinite;
}

/* 缓慢脉冲动画 */
@keyframes ping-slow {
  0% {
    transform: scale(0.8);
    opacity: 0.3;
  }
  50% {
    transform: scale(1.5);
    opacity: 0.5;
  }
  100% {
    transform: scale(0.8);
    opacity: 0.3;
  }
}

.animate-ping-slow {
  animation: ping-slow 2s ease-in-out infinite;
}

.typing-indicator {
  box-shadow: 0 4px 15px rgba(129, 83, 255, 0.1), 0 1px 3px rgba(147, 220, 36, 0.1);
  backdrop-filter: blur(8px);
}

/* 发送按钮活跃状态 */
.send-btn-active {
  animation: send-btn-pulse 3s infinite ease-in-out;
}

@keyframes send-btn-pulse {
  0% {
    box-shadow: 0 0 5px rgba(129, 83, 255, 0.3);
  }
  50% {
    box-shadow: 0 0 15px rgba(129, 83, 255, 0.5), 0 0 30px rgba(147, 220, 36, 0.3);
  }
  100% {
    box-shadow: 0 0 5px rgba(129, 83, 255, 0.3);
  }
}

/* 输入框焦点线条效果 */
.input-focus-effect.focused::after {
  background: linear-gradient(90deg, #8153ff, #93dc24);
}
</style> 